package janino.resource;

import j2me.util.collections.HashMap;
import j2me.util.collections.HashSet;
import j2me.util.collections.Map;
import j2me.util.collections.Set;
import java.io.IOException;
import java.util.Enumeration;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

/**
 * A {@link org.codehaus.janino.util.resource.FileResourceFinder} that finds
 * file resources in a directory. The name of the file is constructed by
 * concatenating a dirctory name with the resource name such that slashes in the
 * resource name map to file separators.
 */
public class DirectoryResourceFinder extends FileResourceFinder {

    private final String directory;
    //Associa diretorios a lista de arquivos
    private final Map subdirectoryNameToFiles = new HashMap(); // String directoryName => Set => File

    /**
     * @param directory o diretorio para usar como base da busca
     */
    public DirectoryResourceFinder(String directory) {
        this.directory = directory;
    }

    public final String toString() {
        return "dir:" + this.directory;
    }

    // Implement FileResourceFinder.
    protected final String findResourceAsFile(String resourceName) {
        // Determine the subdirectory name (null for no subdirectory).
        int idx = resourceName.lastIndexOf('/');

        String subdirectoryName = (idx == -1 ? "" : resourceName.substring(0, idx + 1));

        Set files = (Set) this.subdirectoryNameToFiles.get(subdirectoryName); // String directoryName => Set => File Url

        if (files == null) {
            files = new HashSet();

            String subDiretorio = this.directory + subdirectoryName;

            FileConnection conn = null;

            try {
                conn = (FileConnection) Connector.open((subdirectoryName == null ? directory : subDiretorio));
                Enumeration nomes = conn.list();
                if (nomes != null) {
                    while (nomes.hasMoreElements()) {
                        String nome = (String) nomes.nextElement();
                        files.add(conn.getURL() + nome);
                    }
                    nomes = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (IOException ex) {
                    }
                }
            }

            this.subdirectoryNameToFiles.put(subdirectoryName, files);
        }

        String url = this.directory + resourceName;

        if (!files.contains(url)) {
            return null;
        }

        return url;
    }
}
